package com.simba.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.simba.framework.util.applicationcontext.ApplicationContextUtil;
import com.simba.framework.util.code.EncryptUtil;
import com.simba.framework.util.json.JsonResult;
import com.simba.jwt.constant.JwtConstantData;
import com.simba.jwt.util.JwtUtil;
import com.simba.registry.util.RegistryUtil;
import com.simba.sdk.UserSdk;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * Created by shuoGG on 2018/9/18
 */
public class JwtFilter extends ZuulFilter {

    private static final String BEARER_HEAD = "bearer;";

    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * filter执行顺序, 通过数字指定, 优先级为0最高
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启该filter
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String authHeader = request.getHeader("authorization");
        if (StringUtils.isEmpty(authHeader) || !authHeader.startsWith(BEARER_HEAD)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (username == null || password == null) {
                authFail(ctx, "无authorization头");
                return null;
            }
            UserSdk userSdk = ApplicationContextUtil.getBean(UserSdk.class);
            JsonResult loginRet = userSdk.getLogin(username, password);
            if (loginRet.getCode() == 200) {
                returnAuthToken(ctx);
            } else {
                authFail(ctx, "无authorization头");
            }
            return null;
        }
        String token = authHeader.substring(BEARER_HEAD.length()); // 滤掉bearer;
        Claims claims = JwtUtil.parseJWT(token);
        if (!checkClaims(ctx, claims)) return null;
        String content = (String) claims.get(JwtConstantData.tokenContentName);
        request.setAttribute(JwtConstantData.requestAttributeName, content);
        authSuccess(ctx);
        return null;
    }

    private boolean checkClaims(RequestContext ctx, Claims claims) {
        Date expiration = claims.getExpiration();
        if (expiration.before(new Date())) {
            authFail(ctx, "token过期");
            return false;
        }
        String audience = claims.getAudience();
        if (!audience.equals(RegistryUtil.get("jwt.audience"))) {
            authFail(ctx, "token无效");
            return false;
        }
        String issuer = claims.getIssuer();
        if (!issuer.equals(RegistryUtil.get("jwt.issuer"))) {
            authFail(ctx, "token无效");
            return false;
        }
        return true;
    }

    private void returnAuthToken(RequestContext ctx) {
        String username = ctx.getRequest().getParameter("username");
        String password = ctx.getRequest().getParameter("password");
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
        ctx.set("isSuccess", true);
        ctx.getResponse().setHeader("authorization", JwtUtil.createJWT(EncryptUtil.md5(username + password)));
    }

    private void authSuccess(RequestContext ctx) {
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
        ctx.set("isSuccess", true);
    }

    private void authFail(RequestContext ctx, String errMsg) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(400);
        ctx.setResponseBody(errMsg);
        ctx.set("isSuccess", false);
    }
}
